//index.js
var util = require('../../utils/util.js');
//获取应用实例
const app = getApp()

Page({
  data: {
    array: [],
    index: 0,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    date: util.formatTime(new Date())
  },
  bindDateChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  bindPickerChange: function(e) {
    console.log(e);
    console.log(this.data.array)
    this.setData({
      index: e.detail.value,
      arrayValue: this.data.array[e.detail.value].name
    });
  },
  onLoad: function() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    var that = this;
    wx.request({
      url: util.getUrl() + '/type/1', // 仅为示例，并非真实的接口地址
      success(res) {

        console.log(res.data)
        that.setData({
          array: res.data
        });
      }
    })
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  test: function(e) {
    console.log(e);

    wx.request({
      url: 'https://finapp.liuchang.red:8443/pay/6', // 仅为示例，并非真实的接口地址
      success(res) {
        console.log(res.data)
      }
    })
  },
  formSubmit: function(e) {
    var that = this;
    console.log(e);
    //提交
    wx.request({
      url: util.getUrl() + '/pay',
      data: {
        'date': e.detail.value.date,
        'type': that.data.array[e.detail.value.type].id,
        'name': e.detail.value.name,
        'money': e.detail.value.money
      },
      method: 'POST',
      success: function(requestRes) {
        console.log(requestRes);
        if (requestRes.data == "success") {
          wx.showToast({
            title: '成功',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            nameValue: '',
            moneyValue: ''
          });
        } else {
          wx.showToast({
            title: '失败',
            icon: 'success',
            duration: 2000
          })
        }

      },
      fail: function() {},
      complete: function() {}
    });
  }
})